<?php

declare(strict_types=1);

namespace App\CustHub\Listener;

use App\CustHub\Event\ContactBlackListAddAfter;
use App\CustHub\Helpers\Robot;
use App\CustHub\Mapper\ChContactBlackMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Mapper\ChRoomMemberMapper;
use App\CustHub\Model\ChContactBlack;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChRoomMember;
use App\Robot\Service\RobotApiService;
use Hyperf\Coroutine\Coroutine;
use Hyperf\DbConnection\Db;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;

/**
 * 黑名单
 */
#[Listener]
class ContactBlackListAddListener implements ListenerInterface
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            ContactBlackListAddAfter::class,
        ];
    }

    public function process(object $event): void
    {
        $userIds = $event->userIds;
        $mainUid = $event->mainUid;
        stdout_log()->info('黑名单-添加-'.json_encode($userIds));
        $blackList = ChContactBlack::query()
            ->where('main_uid',$mainUid)
            ->whereIn('user_id',$userIds)
            ->get()->toArray();
        foreach ($blackList as $item){
            $userId = $item['user_id'];
            $robotList = ChRobot::query()
                ->select(['id','user_id'])
                ->where('main_uid',$mainUid)
                ->where('user_id','<>',$userId)
                ->where('login_status',1)
                ->get();

            $robotIds = $robotList->pluck('id')->toArray();
            $robotUserIds = $robotList->pluck('user_id')->toArray();

            $roomMemberList = ChRoomMember::query()
                ->select(['room_wxid','user_id'])
                ->with(['room' => function ($query) use ($robotIds) {
                    $query->select(['id','room_name','room_wxid'])
                        ->with(['robots' => function ($query) use ($robotIds){
                            $query->select(['id','nickname','server_id','uuid'])->whereIn('id', $robotIds);
                        }]);
                }])
                ->where('user_id',$userId)
                ->where('is_owner',0)
                ->where('is_out',0)
                ->whereHas('room.roomMembers', function ($query) use ($robotUserIds) {
                    $query->whereIn('user_id', $robotUserIds)
                        ->where(function ($query) {
                            $query->where('is_owner', 1)   // 机器人是群主
                            ->orWhere('is_admin', 1);  // 或者机器人是管理员
                        });
                })
                ->whereHas('room',function ($query) use ($robotIds){
                    $query->whereHas('robots',function ($query) use ($robotIds){
                        $query->whereIn('robot_id',$robotIds);
                    });
                })->get()->toArray();
            stdout_log()->info('黑名单'.$userId.'-提出群聊-'.json_encode(array_column($roomMemberList,'room_wxid')));
            foreach ($roomMemberList as $roomMemberItem){
                if(!empty($roomMemberItem['room']['robots'])){
                    $robot = array_shift($roomMemberItem['room']['robots']);
                    $robotService = make(\App\Common\Robot\Robot::class,[$robot['server_id'],$robot['uuid']])->gateway();
                    // 移除群成员
                    $result = $robotService->removeRoomMember($roomMemberItem['room_wxid'],[$userId]);
                    if($result !== false){
                        //变更本地用户在群状态
                        $this->container->get(ChRoomMemberMapper::class)->outRoom($roomMemberItem['room_wxid'],$userId);
                    }
                }
                Coroutine::sleep(rand(1,2));
            }

        }
    }

}